import { appModel } from '@/api/app';
import { IUser } from '@/api/system/user';
import { filterAsyncRoutes } from '@/helper/router';
import { asyncRoutes } from '@/router/routes';
import { defineStore } from 'pinia';
import { reactive, toRefs } from 'vue';

interface Permission {
  authRoutes: any[];
  userInfo: IUser
}

export const usePermissionStore = defineStore('permission', () => {
  const store: Permission = reactive({
    authRoutes: [],
    userInfo: null
  });

  async function generateRoutes() {
    const { data: { data } } = await appModel.getUserInfo();
    const permList = data.menus.map((item) => item.url);
    store.userInfo = data;
    store.authRoutes = filterAsyncRoutes(asyncRoutes, permList);
  }

  function clearPermissin() {
    store.authRoutes = [];
    store.userInfo = null;
  }

  return {
    ...toRefs(store),
    generateRoutes,
    clearPermissin
  };
});
